/**
 * Created by whw on 2017/1/12.
 */
$(function () {
    var getShopMsg = '/shop/getUserShop',
        getShopData = '/home/searchProvideInfos',
        logoImg = $('.shopImg img'),
        shopTitle = $('.shopmsg h4'),
        shopState = $('#shopState'),
        shopTotal = $('#shopTotal'),
        shopHot = $('#shopHot'),
        jrollinit = null,
        dataTypes = '',
        qiye = '<img src="img/shop/icon-qyyrz.png" alt=""><span style="">企业已认证</span>',
        amountReverse = getQueryString('amountReverse') || '',
        priceReverse = getQueryString('priceReverse') || '',
        uuid = getQueryString('id') || '',
        setmeatType = function (obj) {
            // "uuid" : "xxxx",            //用户uuid
            //     "signature" : "xxx",        //访问签名
            // "warehouse":"北京"          // 所在地的搜索
            obj.uuid = uuid;
            obj.pageSize = obj.pageSize || 10;
            obj.amountReverse = amountReverse; // 数量排序
            obj.priceReverse = priceReverse; // 价格排序
            obj.offset = obj.offset || 0;
            dataTypes = 'uuid='+obj.uuid+'&updateDate='+'&amountReverse='+amountReverse+'&priceReverse='+priceReverse +'&offset='+obj.offset+'&pageSize='+obj.pageSize;
            return dataTypes;
        },requestData = function (obj,fun) {
            $.ajax({
                url: host + getShopData,
                type: 'post',
                data: obj,
                success: function (data) {
                    fun(data)
                }
            });
        };
    $.ajax({
        url:host + getShopMsg,
        data:'uuid='+getQueryString('id'),
        dataType:'json',
        success: function (data) {
            var data = data.data;
            data.shopLogo = data.shopLogo || 'img/user.png'
            if(data.authenticationStatus != 1 && data.auditStatus == 2){
                shopState.html(qiye);
            }
            logoImg.attr('src', data.shopLogo)
            shopTitle.text(data.shopName)
            share(data.shopName)
            $('span', shopTotal).text(data.provideNum)
            $('span', shopHot).text(data.zhaoNiuReport)
            $('.shopTitle').removeClass('visi')
        },
        error: function (data) {
            console.log(data)
        }
    })
    // 店铺主页
    $('.shopTitle').on('click', function (e) {
       if($(e.target).parents('.shopShare')[0]){
           $('#sharePage').show()
       }else {
           window.location.href = 'shopIntroduction.html?id='+getQueryString('id');
       }
    })
    // 分享
    $('#sharePage').on('click', function () {
        $('#sharePage').hide()
    })
    $('#nav .term li').eq(0).on('click', function () {
        $('#nav .term li').removeClass('blue-color')
        $(this).addClass('blue-color')
        priceReverse = !priceReverse;
        if(!priceReverse) {
            $('.san').eq(1).addClass('toggle-b')
            $('.san').eq(0).removeClass('toggle-t')
        }else {
            $('.san').eq(0).addClass('toggle-t')
            $('.san').eq(1).removeClass('toggle-b')
        }
        // priceReverse = true
        jrollinit.destroy();
        $('#meal-info').empty()
        $('#meal-info').append($('<ul class="container" id="scroller"></ul>'));
        jroll();
        jrollinit.refresh();

    })
    $('#nav .term li').eq(1).on('click', function () {
        $('#nav .term li').removeClass('blue-color')
        $(this).addClass('blue-color')
        amountReverse = !amountReverse;
        if(!amountReverse) {
            $('.san').eq(3).addClass('toggle-b')
            $('.san').eq(2).removeClass('toggle-t')
        }else {
            $('.san').eq(2).addClass('toggle-t')
            $('.san').eq(3).removeClass('toggle-b')
        }
        jrollinit.destroy();
        $('#meal-info').empty()
        $('#meal-info').append($('<ul class="container" id="scroller"></ul>'));
        jroll();
        jrollinit.refresh();

    })
    $('#nav .term li').eq(2).on('click', function () {
        amountReverse = ''
        priceReverse = ''
        $('#nav .term li').removeClass('blue-color')
        $(this).addClass('blue-color')
        $('.san').removeClass('toggle-b')
        $('.san').removeClass('toggle-t')
        jrollinit.destroy();
        $('#meal-info').empty()
        $('#meal-info').append($('<ul class="container" id="scroller"></ul>'));
        jroll();
        jrollinit.refresh();
    })

    // 默认首屏渲染
    jroll();
    function jroll() {
        jrollinit = new JRoll("#meal-info", {
            scrollBarY: true,
            scrollBarFade: true
        });   // jroll 对象

        // // 下拉刷新
        jrollinit.pulldown({
            spinning:false,
            refresh: function(complete) {
                jrollinit.options.page = 1;
                requestData(setmeatType({
                    uuid:uuid,
                    offset: jrollinit.options.page - 1,
                    amountReverse : amountReverse,
                    priceReverse : priceReverse,
                }),function (data) {
                    if (data.success == true) {
                        complete();
                        if(!data.data.length){
                            jrollinit.scroller.innerHTML = '<div id="noIssue" style="text-align: center;margin-top: 100px;"><div><img src="img/noSearch.png"></div><p>店家还没有上架商品</p><div class="jroll-infinite-tip"><a href="javascript:;" id="noresult">换个店家试试</a></div></div>'
                            $('#noresult').on('click', function () {
                                window.location.href = 'supermarket.html';
                            })
                        }else {
                            jrollinit.scroller.innerHTML = "";    //清空内容
                            jrollinit.infinite_callback(data.data);
                        }
                    } else {
                        //无数据则返回什么
                        console.log(data)
                    }
                });
            },
            // topIndex:'26'
        });
        // 无限加载
        jrollinit.infinite({
            options: jrollinit,
            completeTip: '<div class=\"jroll-infinite-tip\" style=\"text-align\: center\;\">俺也是有底线的！</div>',
            loadingTip: '<div class=\"jroll-infinite-tip\" style=\"text-align\: center\;\">正在加载...</div>',
            // template: '<li onclick="fn(this)" ><a  href="deliveryDetails.html?history=true&id={{=_obj.id}}"><div class="row"><div class="col-xs-4" id="photo"><img src={{=_obj.imageList[0]?_obj.imageList[0]:"img\/defaultImg.png"}}></div><div class="col-xs-8 "><p>{{=_obj.meatCategory[0]?_obj.meatCategory[0]:"暂无数据"}}</p><p id="price"><span><em>¥{{=_obj.price?_obj.price+ "/吨":"议定"}}</em></span></p><p><span>产地：<em>{{=_obj.country}}</em></span><span id="margin">所在地：{{=_obj.warehouse}}</em></span></p><p><span>数量：<em>{{=Math.round(_obj.amount / 1000 * 100) / 100}}吨</em></span>  <span>供货类型：<em>{{=_obj.provideWay}}</em></p></div></div></a></li>',
            template: '<li data-id={{=_obj.id}} data-xian={{=_obj.provideWay=="期货"?0:1}} onclick="fn(this)"><a href="deliveryDetails.html?shop=true&id={{=_obj.id}}"><div class="row"><div class="photo1"><img src={{=_obj.imageList[0]?_obj.imageList[0]:"img\/defaultImg.png"}}></div><div class="text"><div class="price"><span>￥</span>{{=_obj.price?_obj.price:"议定"}}<span>/吨</span></div><p class="title">{{=_obj.meatCategory[0]?_obj.meatCategory[0]:"暂无数据"}}</p><p class="time">{{=time(_obj.updateDate)}}</p><p><span class="fl">数<span style="visibility: hidden;">量</span>量：<span class="blue-color">{{=Math.round(_obj.amount / 1000 * 100) / 100}} </span>吨</span><span class="fr">厂号品牌：{{=_obj.factoryNo}}</span></p><p><span class="fl">所在地：<span>{{=_obj.warehouse}} </span></span><span class="fr">产品产地：{{=_obj.country}}</span></p><div class="xian {{=_obj.provideWay==\"期货\"?\"huang\":\"\"}}">{{=_obj.provideWay=="期货"?"期":"现"}}</div></div></div></a> </li>',
            getData: function (page, callback) {

                    requestData(setmeatType({
                        uuid:uuid,
                        offset: page - 1,
                        amountReverse : amountReverse,
                        priceReverse : priceReverse,
                    }),function (data) {
                        if (data.success == true) {
                            if(!data.total){
                                jrollinit.scroller.innerHTML = '<div id="noIssue" style="text-align: center;margin-top: 100px;"><div><img src="img/noSearch.png"></div><p>店家还没有上架商品</p><div class="jroll-infinite-tip"><a href="javascript:;" id="noresult">换个店家试试</a></div></div>'
                                $('#noresult').on('click', function () {
                                    window.location.href = 'supermarket.html';
                                })
                            }else{
                                jrollinit.options.total = Math.ceil(data.total / 10);
                                if(page >= jrollinit.options.total){
                                    jrollinit.options.page = jrollinit.options.total;
                                }
                                callback(data.data)
                            }

                        } else {
                            //无数据则返回什么
                            console.log(data)
                        }
                    });
            },
        });

        jrollinit.refresh();
        return jrollinit;
    };
})
function share(personal,img){
    var titleShare = personal,
        desc = '邀请您浏览他在找牛网的店铺。找牛网清真交易平台';
    if(img==null||img=="undefined"){
        img='http://m.zhaoniuw.com/img/icon_share.jpg';
    }
    $.ajax({
        url:wechathost+shareurl + shareparm,
        type:'post',
        success:function(res){

            var json = eval('(' + res + ')');
            wx.config({
                debug: false, // 开启调试模￿调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印￿
                appId: 'wx554a3c93d558ae03', // 必填，公众号的唯一标识
                timestamp:json.data.timestamp , // 必填，生成签名的时间￿
                nonceStr: json.data.nonceStr, // 必填，生成签名的随机￿
                signature: json.data.signature,// 必填，签名，见附￿
                jsApiList: [
                    'onMenuShareTimeline',
                    'onMenuShareAppMessage'


                ] // 必填，鿀要使用的JS接口列表，所有JS接口列表见附￿
            });

            wx.ready(function(){


                wx.checkJsApi({
                    jsApiList: ['onMenuShareAppMessage'], // 需要检测的JS接口列表，所有JS接口列表见附￿
                    success: function(res) {


                        // 以键值对的形式返回，可用的api值true，不可用为false
                        // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                    }
                });
                wx.onMenuShareTimeline({
                    title: titleShare, // 分享标题
                    link:shareUrl,
                    imgUrl: img, // 分享图标
                    success: function () {

                    },
                    cancel: function () {
                        // 用户取消分享后执行的回调函数
                    }
                });

                wx.onMenuShareAppMessage({
                    title:titleShare, // 分享标题
                    desc: desc, // 分享描述
                    link: shareUrl, // 分享链接
                    imgUrl: img, // 分享图标
                    type: '', // 分享类型,music、video或link，不填默认为link
                    dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                    success: function () {
                    },
                    cancel: function () {
                        // 用户取消分享后执行的回调?ǽ敿
                    }
                });


            });

            wx.error(function(res){

            });


        }
    });
}